package com.winning.bi.amqp;

import java.io.IOException;

import org.springframework.util.SerializationUtils;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.MessageProperties;
import com.winning.bi.data.Message;
import com.winning.bi.processer.EventProcesser;

/**
 * 
 * 接收消息方法
 * 
 * @author 张大川
 *
 */
public class ReceiveMessageUtils {

	private Channel channel;

	private Connection connection;

	/**
	 * 
	 * @param <T>
	 * @param queueName
	 *            队列名称
	 * @param eventProcesser
	 *            处理事件实例
	 * @param clazz
	 *            要接收的消息类型
	 * @throws Exception
	 */
	public <T> void receiveMessage(String queueName, EventProcesser eventProcesser) throws Exception {

		channel = connection.createChannel();
		channel.queueDeclare(queueName, true, false, false, null);
		System.out.println(queueName);
		channel.basicQos(1);// 一次只接收一个消息

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {

				boolean b = false;
				b = eventProcesser.process((Message) SerializationUtils.deserialize(body), queueName);
				//System.out.println(envelope.getDeliveryTag());
				if (b) {

					channel.basicAck(envelope.getDeliveryTag(), false); // 发送确认
				} else {
					//System.out.println("失败");
					channel.basicAck(envelope.getDeliveryTag(), false); // 发送确认

					channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, body);
					// channel.basicReject(envelope.getDeliveryTag(), true);
				}
			}
		};

		channel.basicConsume(queueName, consumer);

	}

	public ReceiveMessageUtils(Connection connection) {
		super();
		this.connection = connection;
	}

	public void close() throws Exception {

		connection.close();
	}

}